import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { dataList } from '@/pages/Defense/System/Trouble/service';
import CheckModule from '@/components/CheckModule';
import {
  PersonRecordItem,
  TroubleMonthCountItem,
  TroubleSystemListItem,
} from '@/pages/Defense/System/Trouble/data';
import { Col, Drawer, Row, Tag } from 'antd';
import {
  monthCountDataList,
  personDataList,
  postCountDataList,
} from '@/pages/Defense/System/Trouble/service';
import { Gauge, Pie } from '@ant-design/charts';

let date = new Date();
let year = date.getFullYear();
let yearE = new Map();
for (let i = year; i > year - 3; i--) {
  yearE.set(i, {
    text: i + '年',
  });
}
let yearEnum = yearE;
const TroubleSystemPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<TroubleSystemListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
                (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '名称',
      dataIndex: 'year',
      search: false,
      render: (_, record) => (
        <span style={{ whiteSpace: 'pre-wrap' }}>
          {record?.year}年{record?.month}月隐患统计
        </span>
      ),
    },
    {
      title: '年份',
      dataIndex: 'year',
      initialValue: year,
      hideInTable: true,
      valueEnum: yearEnum,
    },
    {
      title: '隐患项',
      tooltip: '隐患项数量',
      search: false,
      children: [
        {
          title: '总数',
          dataIndex: 'itemNum',
          search: false,
          align: 'center',
        },
        {
          title: '已完成',
          dataIndex: 'finishedItemNum',
          search: false,
          align: 'center',
        },
        {
          title: '未完成',
          dataIndex: 'unfinishedItemNum',
          search: false,
          align: 'center',
        },
        {
          title: '完成率',
          tooltip: '完成率=(已完成/总数)*100',
          dataIndex: 'unfinishedItemNum',
          search: false,
          align: 'center',
          render: (_, record) => (
            <span style={{ whiteSpace: 'pre-wrap' }}>
              {((record?.finishedItemNum / record?.itemNum) * 100).toFixed(2)}%
            </span>
          ),
        },
      ],
    },
    {
      title: '下发任务',
      tooltip: '下发任务数量',
      search: false,
      children: [
        {
          title: '总数',
          dataIndex: 'total',
          search: false,
          align: 'center',
        },
        {
          title: '已完成',
          dataIndex: 'finished',
          search: false,
          align: 'center',
        },
        {
          title: '未完成',
          dataIndex: 'unfinished',
          search: false,
          align: 'center',
        },
        {
          title: '完成率',
          tooltip: '完成率=(已完成/总数)*100',
          dataIndex: 'total',
          search: false,
          align: 'center',
          render: (_, record) => (
            <span style={{ whiteSpace: 'pre-wrap' }}>
              {((record?.finished / record?.total) * 100).toFixed(2)}%
            </span>
          ),
        },
      ],
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => [
        <a
          key="view1"
          onClick={() => {
            setCurrentYear(record.year);
            setCurrentMonth(record.month);
            // setShowDetail(true);
            setShowMonthItemCount(true);
          }}
        >
          隐患项
        </a>,
        <a
          key="view"
          onClick={() => {
            // setCurrentRow(record);
            // setShowDetail(true);

            setCurrentYear(record.year);
            setCurrentMonth(record.month);
            // setShowDetail(true);
            setShowPostCount(true);
          }}
        >
          岗位
        </a>,
      ],
    },
  ];

  const itemCountActionRef = useRef<ActionType>();
  const itemCountColumns: ProColumns<TroubleMonthCountItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
                (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '危险源',
      dataIndex: 'source',
      search: false,
    },
    {
      title: '危险源分类',
      dataIndex: 'sourceType',
      search: false,
      valueEnum: {
        1: {
          text: '人的不安全行为',
        },
        2: {
          text: '物的不安全状态',
        },
        3: {
          text: '不良环境',
        },
        4: {
          text: '管理缺陷',
        },
      },
    },
    // {
    //   title: '危险源类型',
    //   dataIndex: 'riskType',
    //   search: false,
    //   render: (_, record) => (
    //     <>
    //       {record?.possibleResult?.map((name, index) => (
    //         <Tag key={name + index + record.riskId}>{name}</Tag>
    //       ))}
    //     </>
    //   ),
    // },
    {
      title: '场所/位置/作业',
      dataIndex: 'place',
      search: false,
    },
    {
      title: '隐患等级',
      dataIndex: 'level',
      search: false,
      valueEnum: {
        2: {
          text: '一般',
          color: '#E1E13A',
        },
        4: {
          text: '重大',
          color: '#FF0000',
        },
      },
    },
    {
      title: '排查频次',
      dataIndex: 'frequency',
      valueEnum: {
        1: {
          text: '每日一次',
        },
        2: {
          text: '每周一次',
        },
        3: {
          text: '每月一次',
        },
        4: {
          text: '每季度一次',
        },
        5: {
          text: '每年一次',
        },
        6: {
          text: '每半年一次',
        },
        0: {
          text: '仅一次',
        },
      },
    },
    {
      title: '整改措施',
      dataIndex: 'measure',
    },
    {
      title: '整改建议',
      dataIndex: 'responsibility',
    },
    {
      title: '下发任务(数量)',
      tooltip: '下发任务数量',
      search: false,
      children: [
        {
          title: '总数',
          dataIndex: 'total',
          search: false,
          align: 'center',
        },
        {
          title: '已完成',
          dataIndex: 'finished',
          search: false,
          align: 'center',
        },
        {
          title: '未完成',
          dataIndex: 'unfinished',
          search: false,
          align: 'center',
        },
        {
          title: '完成率',
          tooltip: '完成率=(已完成/总数)*100',
          dataIndex: 'total',
          search: false,
          align: 'center',
          render: (_, record) => (
            <span style={{ whiteSpace: 'pre-wrap' }}>
              {((record?.finished / record?.total) * 100).toFixed(2)}%
            </span>
          ),
        },
      ],
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      search: false,
      hideInDescriptions: true,
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentTrouble(record.troubleId);
            setShowPersonList(true);
            // setCurrentRow(record);
            // setShowDetail(true);
          }}
        >
          查看
        </a>,
      ],
    },
  ];
  const postCountActionRef = useRef<ActionType>();
  const postCountColumns: ProColumns<TroubleSystemListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
                (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '岗位名称',
      dataIndex: 'name',
      search: false,
    },
    {
      title: '员工数',
      dataIndex: 'personNum',
      search: false,
    },
    {
      title: '年份',
      dataIndex: 'year',
      initialValue: year,
      hideInTable: true,
      valueEnum: yearEnum,
    },
    {
      title: '隐患项',
      tooltip: '隐患项数量',
      search: false,
      children: [
        {
          title: '总数',
          dataIndex: 'itemNum',
          search: false,
          align: 'center',
        },
        {
          title: '已完成',
          dataIndex: 'finishedItemNum',
          search: false,
          align: 'center',
        },
        {
          title: '未完成',
          dataIndex: 'unfinishedItemNum',
          search: false,
          align: 'center',
        },
        {
          title: '完成率',
          tooltip: '完成率=(已完成/总数)*100',
          dataIndex: 'unfinishedItemNum',
          search: false,
          align: 'center',
          render: (_, record) => (
            <span style={{ whiteSpace: 'pre-wrap' }}>
              {((record?.finishedItemNum / record?.itemNum) * 100).toFixed(2)}%
            </span>
          ),
        },
      ],
    },
    {
      title: '下发任务(数量)',
      tooltip: '下发任务数量',
      search: false,
      children: [
        {
          title: '总数',
          dataIndex: 'total',
          search: false,
          align: 'center',
        },
        {
          title: '已完成',
          dataIndex: 'finished',
          search: false,
          align: 'center',
        },
        {
          title: '未完成',
          dataIndex: 'unfinished',
          search: false,
          align: 'center',
        },
        {
          title: '完成率',
          tooltip: '完成率=(已完成/总数)*100',
          dataIndex: 'total',
          search: false,
          align: 'center',
          render: (_, record) => (
            <span style={{ whiteSpace: 'pre-wrap' }}>
              {((record?.finished / record?.total) * 100).toFixed(2)}%
            </span>
          ),
        },
      ],
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      search: false,
      hideInDescriptions: true,
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentPost(record.countId);
            setItemHasSource(true);
            setShowMonthItemCount(true);
          }}
        >
          查看
        </a>,
      ],
    },
  ];

  const personCountActionRef = useRef<ActionType>();
  const personCountColumns: ProColumns<PersonRecordItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
                (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '责任人',
      dataIndex: 'name',
      search: false,
    },
    {
      title: '下发时间',
      dataIndex: 'createTime',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '未处理',
          color: '#FF0000',
        },
        1: {
          text: '已处理',
          color: '#00ff43',
        },
      },
    },
    {
      title: '位置',
      dataIndex: 'place',
      search: false,
    },
    {
      title: '上报时间',
      dataIndex: 'updateTime',
      search: false,
      render: (_, record) => {
        if (record.status == 1) {
          return <span>{record.updateTime}</span>;
        }
        return <>-</>;
      },
    },
  ];

  const [showMonthItemCount, setShowMonthItemCount] = useState<boolean>(false);
  const [itemHasSource, setItemHasSource] = useState<boolean>(false);
  const [showPostCount, setShowPostCount] = useState<boolean>(false);
  const [showPersonList, setShowPersonList] = useState<boolean>(false);
  const [currentYear, setCurrentYear] = useState<number>();
  const [currentMonth, setCurrentMonth] = useState<number>();
  const [currentPost, setCurrentPost] = useState<number>(0);
  const [currentTrouble, setCurrentTrouble] = useState<number>(0);
  const [pieData, setPieData] = useState<[]>([]);
  const [percent, setPercent] = useState<number>(0);

  return (
    <CheckModule code={'SC'}>
      <PageContainer waterMarkProps={{ content: '' }}>
        <ProTable<TroubleSystemListItem>
          headerTitle="隐患治理"
          actionRef={actionRef}
          rowKey="month"
          bordered
          search={{
            labelWidth: 120,
          }}
          request={dataList}
          pagination={false}
          columns={columns}
        />
        <Drawer
          width={'80%'}
          visible={showMonthItemCount}
          destroyOnClose={true}
          onClose={() => {
            if (!itemHasSource) {
              setCurrentMonth(undefined);
              setCurrentYear(undefined);
            }
            setCurrentPost(0);
            setShowMonthItemCount(false);
            setItemHasSource(false);
          }}
          closable={false}
        >
          <Row gutter={16}>
            <Col className="gutter-row" span={12}>
              <Pie
                data={pieData}
                appendPadding={10}
                angleField={'value'}
                colorField={'type'}
                height={300}
                legend={{
                  layout: 'horizontal',
                  position: 'top',
                }}
                color={({ type }) => {
                  console.log(type);
                  // alert(type)
                  if (type === '较小风险') {
                    return '#0000FF';
                  }
                  if (type === '一般风险') {
                    return '#E1E13A';
                  }
                  if (type === '较大风险') {
                    return '#FFA500';
                  }
                  if (type === '重大风险') {
                    return '#FF0000';
                  }
                  return '#808080';
                }}
              />
            </Col>
            <Col className="gutter-row" span={12}>
              <Gauge
                range={{
                  ticks: [0, 1 / 4, 1 / 2, 3 / 4, 1],
                  color: ['#FF0000', '#FFA500', '#E1E13A', '#0000FF', '#0000FF'],
                }}
                axis={{
                  label: {
                    formatter(v) {
                      return Number(v) * 100;
                    },
                  },
                  subTickLine: {
                    count: 3,
                  },
                }}
                percent={percent}
                type={'meter'}
                height={300}
              />
            </Col>
          </Row>

          <ProTable<TroubleMonthCountItem>
            headerTitle="隐患项"
            actionRef={itemCountActionRef}
            rowKey="troubleId"
            bordered
            search={false}
            // search={{
            //   labelWidth: 120,
            // }}
            // request={monthCountDataList}
            request={async () => {
              let newVar = await monthCountDataList({
                year: currentYear,
                month: currentMonth,
                postId: currentPost,
              });
              setPieData(newVar.data.count);
              setPercent(newVar.data.percent);
              return {
                data: newVar.data.list,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: newVar.data.list.length,
              };
            }}
            pagination={false}
            columns={itemCountColumns}
          />
        </Drawer>
        <Drawer
          width={'60%'}
          visible={showPostCount}
          destroyOnClose={true}
          onClose={() => {
            setCurrentPost(0);
            setShowPostCount(false);
          }}
          // closable={false}
        >
          <ProTable<TroubleSystemListItem>
            headerTitle="岗位统计"
            actionRef={postCountActionRef}
            rowKey="countId"
            bordered
            search={false}
            // search={{
            //   labelWidth: 120,
            // }}
            // request={monthCountDataList}
            request={async () => {
              let newVar = await postCountDataList({ year: currentYear, month: currentMonth });
              console.log(newVar);
              return {
                data: newVar.data,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: newVar.data.length,
              };
            }}
            pagination={false}
            columns={postCountColumns}
          />
        </Drawer>
        <Drawer
          width={'60%'}
          visible={showPersonList}
          destroyOnClose={true}
          onClose={() => {
            setCurrentTrouble(0);
            setShowPersonList(false);
          }}
          // closable={false}
        >
          <ProTable<PersonRecordItem>
            headerTitle="下发清单"
            actionRef={personCountActionRef}
            rowKey="troubleRecordId"
            bordered
            search={false}
            // search={{
            //   labelWidth: 120,
            // }}
            // request={monthCountDataList}
            request={async () => {
              let newVar = await personDataList({
                year: currentYear,
                month: currentMonth,
                postId: currentPost,
                troubleId: currentTrouble,
              });
              console.log(newVar);
              return {
                data: newVar.data,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: newVar.data.length,
              };
            }}
            pagination={false}
            columns={personCountColumns}
          />
        </Drawer>
      </PageContainer>
    </CheckModule>
  );
};

export default TroubleSystemPage;
